const tree = function tree(data, pid = '0', result = []) {
  data.forEach((e) => {
    const el = e;
    el.children = el.children || [];
    if (el.pid === pid) {
      result.push(el);
      const { _id: id } = el;
      tree(data, id, el.children);
    }
  });
  return result;
};

module.exports = {
  /**
   * 菜单排序
   */
  async menuSort(req) {
    await req.menusModel.menuSort(req.params);
    return {};
  },
  /**
   * 获取菜单
  */
  async getMenus(req) {
    const result = await req.menusModel.getMenus(req.query);
    return tree(JSON.parse(JSON.stringify(result)));
  },
  /**
   * 添加
  */
  async addMenu(req, { boom }) {
    const {
      routename,
    } = req.payload;
    const routenameExist = await req.menusModel.isExist('routename', routename);
    if (routenameExist) {
      return boom.badRequest('routename已存在');
    }
    const result = await req.menusModel.addMenus(req.payload);
    return result;
  },

  /**
   * 根据ID获取单个菜单信息
   */
  async getMenuById(req) {
    const result = await req.menusModel.getMenuById(req.params.id);
    return result;
  },

  /**
   * 根据ID删除菜单
   */
  async deleteMenuById(req, { boom }) {
    const { _id: pid } = await req.menusModel.getMenuById(req.params.id);
    const nodes = await req.menusModel.getChildrenNodes(pid);
    if (nodes.length) {
      return boom.badRequest('请先删除子节点');
    }
    await req.menusModel.deleteMenuById(req.params.id);

    return {};
  },

  /**
   * 根据ID更新菜单信息
  */
  async updateMenuById(req, { boom }) {
    const {
      menuname,
    } = req.payload;
    const menu = await req.menusModel.getMenuById(req.params.id);
    if (menu.menuname !== menuname) {
      const menunameExist = await req.menusModel.isExist('menuname', menuname);
      if (menunameExist) {
        return boom.badRequest('菜单已存在');
      }
    }
    await req.menusModel.updateMenuById(req.params.id, req.payload);
    return {};
  },

  /**
   * 判断字段值是否存在
  */
  async isExist(req) {
    const { field, value } = req.query;
    const result = await req.menusModel.isExist(field, value);
    return Boolean(result);
  },
};
